package com.bondar.task5;

import java.util.ArrayList;
import java.util.concurrent.atomic.AtomicInteger;

public class Bank {

	private final ArrayList<Account> accounts;
	private AtomicInteger failedTransfers;

	public Bank() {
		accounts = new ArrayList<Account>();
		failedTransfers = new AtomicInteger();
	}

	public void transfer(int from, int to, int amount) throws Exception {
		// lock account with min id
		int min = Math.min(from, to);
		Account acc1, acc2;
		
		if (from != min) {
			acc1 = accounts.get(to);
			acc2 = accounts.get(from);
		} else {
			acc1 = accounts.get(from);
			acc2 = accounts.get(to);
		}
		
		synchronized (acc1) {
			synchronized (acc2) {
				if (acc1.withdraw(amount)) {	
					acc2.deposit(amount);
				} else {	
					failedTransfers.incrementAndGet();	
				}
			}
		}
	}

	public int getTotal() {
		int total = 0;
		for (int i = 0; i < accounts.size(); i++) {
			total += accounts.get(i).getBalance();
		}
		return total;
	}

	public void addAccount(Account account) {
		accounts.add(account);
	}

	public int accounts() {
		return accounts.size();
	}

	public Account getAccount(int nextInt) {
		return accounts.get(nextInt);
	}
	
	public int getFailedTransfers() {
		return failedTransfers.get();
	}
}
